<template>
  <van-icon
    color="#777"
    :class="value ? 'success' : ''"
    :name="value ? 'star' : 'star-o'"
    @click="onCollect"
  />
</template>

<script>
import { addCollection, deleteCollection } from '@/api/article.js'
import { mapState } from 'vuex'

export default {
  name: 'ArticleCollection',
  data() {
    return {}
  },
  methods: {
    async onCollect() {
      // 防止用户不断的点击发起请求
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '操作中...',
        forbidClick: true // 是否禁止背景点击
      })

      // 判断是否登陆状态
      if (this.user) {
        try {
          // 1.判断是否收藏了
          if (this.value) {
            // 2.收藏了，发起取消收藏
            await deleteCollection(this.articleId)
            this.$toast.success('取消收藏')
          } else {
            // 3.未收藏，发起收藏请求
            await addCollection(this.articleId)
            this.$toast.success('收藏成功')
          }

          this.$emit('input', !this.value) // 更新状态
        } catch (error) {
          console.log(error)
          this.$toast.fail('操作失败，请稍后重试')
        }
      } else {
        // 未登录,提示登录,并且跳转登录页
        this.$toast.fail('请先登录')
        this.$router.push('/login')
      }
    }
  },
  props: {
    value: {
      type: [Number, Boolean],
      required: true
    },
    articleId: {
      type: [Number, Object, String],
      required: true
    }
  },
  computed: {
    ...mapState(['user'])
  }
}
</script>

<style scoped lang="less">
// 文章收藏后颜色
.success {
  color: rgba(250, 223, 68) !important;
}
</style>
